package cn.njyd.corejava.thread.myday03;

import java.util.concurrent.ThreadLocalRandom;

class Car {
    private String name;
    private int price;
    private boolean flag = true;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

class ProducterCarThread implements Runnable{
    private Car car;

    public ProducterCarThread(Car car) {
        this.car = car;
    }


    @Override
    public void run() {
        String[] names = {"奔驰","宝马","大众","雪佛兰"};
        for (int i=1;i<=20;i++) {
            synchronized (this.car) {
                while(!this.car.isFlag()) {
                    try {
                        this.car.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int index = ThreadLocalRandom.current().nextInt(names.length);
                this.car.setName(names[index]);
                this.car.setPrice(ThreadLocalRandom.current().nextInt(100));
                System.out.println(Thread.currentThread().getName()+"生产出了一辆["+car.getName()+"],价格为"+car.getPrice());
                this.car.setFlag(!this.car.isFlag());
                System.out.println("flag="+this.car.isFlag());
                this.car.notifyAll();
            }
        }


    }
}

class CustomerCarThread implements Runnable{
    private Car car;

    public CustomerCarThread(Car car) {
        this.car = car;
    }


    @Override
    public void run() {
        for (int i=1;i<=10;i++) {
            synchronized (this.car) {
                while(this.car.isFlag()) {
                    try {
                        this.car.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName()+"花费"+this.car.getPrice()+"买了"+this.car.getName());
                this.car.setFlag(!this.car.isFlag());
                System.out.println("flag="+this.car.isFlag());
                this.car.notifyAll();
            }

        }
    }
}

public class ProducterCustomerDemo01 {
    public static void main(String[] args) {
        Car car = new Car();
        ProducterCarThread pct1 = new ProducterCarThread(car);
        CustomerCarThread c1 = new CustomerCarThread(car);
        CustomerCarThread c2 = new CustomerCarThread(car);
        new Thread(pct1).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }
}
